// cloudfunctions/purchase/index.js
const cloud = require('wx-server-sdk')

cloud.init()

const db = cloud.database()
const _ = db.command

exports.main = async (event, context) => {
  console.log('purchase function invoked with event:', event)

  const { userId, productId, model, quantity } = event

  // 参数验证
  if (!userId || !productId || !model || !quantity) {
    console.error('缺少必要的参数', { userId, productId, model, quantity })
    return {
      success: false,
      message: '缺少必要的购买信息。'
    }
  }

  if (typeof quantity !== 'number' || quantity <= 0) {
    console.error('无效的购买数量', quantity)
    return {
      success: false,
      message: '购买数量无效。'
    }
  }

  try {
    // 开启数据库事务
    const transaction = await db.startTransaction()
    console.log('Transaction started')

    // 获取商品详情
    const productRes = await transaction.collection('products').doc(productId).get()
    const product = productRes.data
    console.log('Fetched product details:', product)

    if (!product) {
      console.warn(`商品 ${productId} 不存在`)
      await transaction.rollback()
      return {
        success: false,
        message: '所选商品不存在。'
      }
    }

    if (quantity > product.stock) {
      console.warn(`商品 ${product.name} 库存不足。请求数量: ${quantity}, 可用库存: ${product.stock}`)
      await transaction.rollback()
      return {
        success: false,
        message: `商品 "${product.name}" 库存不足。`
      }
    }

    // 扣减库存并增加销量
    const updateResult = await transaction.collection('products').doc(productId).update({
      data: {
        stock: _.inc(-quantity),
        sales: _.inc(quantity),
        updatedAt: new Date()
      }
    })
    console.log(`更新商品 ${productId} 库存和销量，结果:`, updateResult)

    // 计算总金额
    const totalAmount = product.price * quantity
    console.log(`计算总金额: ￥${totalAmount}`)

    // 创建订单
    const orderRes = await transaction.collection('orders').add({
      data: {
        userId: userId,
        items: [{
          productId: productId,
          model: model,
          quantity: quantity,
          price: product.price,
          total: totalAmount
        }],
        totalAmount: totalAmount,
        status: '待支付',
        createdAt: new Date(),
        updatedAt: new Date()
      }
    })
    console.log('订单创建成功，订单ID:', orderRes._id)

    // 提交事务
    await transaction.commit()
    console.log('Transaction committed successfully')

    return {
      success: true,
      orderId: orderRes._id,
      message: '购买成功。'
    }

  } catch (err) {
    console.error('购买过程中发生错误:', err)
    return {
      success: false,
      message: '购买过程中发生错误，请稍后重试。',
      error: err
    }
  }
}
